package com.example.online.music.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.example.online.music.service.ObjectStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * Oss 相关业务实现类
 *
 * @author yaojianfeng
 */

@Service
public class ObjectStoreServiceImpl implements ObjectStoreService {

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucketName}")
    private String BUCKET_NAME;
    @Value("${aliyun.oss.endPoint}")
    private String ENDPOINT;

    @Override
    public void downloadFile(String objectUrl, String targetFilePath) {

        // 从objectUrl中提取文件名
        String fileName = objectUrl.substring(objectUrl.lastIndexOf('/') + 1);

        String objectKey = getObjectKeyFromUrl(objectUrl);
        //创建文件夹
        File folder = new File(targetFilePath);
        if (!(folder.exists() && folder.isDirectory())) {
            boolean created = folder.mkdirs();
            System.out.println(created ? "创建文件夹成功" : "创建文件夹失败");
        }

        try {
            DownloadFileRequest downloadFileRequest = new DownloadFileRequest(BUCKET_NAME, objectKey);
            // Sets the local file to download to
            downloadFileRequest.setDownloadFile(targetFilePath + fileName);
            // Sets the concurrent task thread count 5. By default it's 1.
            downloadFileRequest.setTaskNum(5);
            // Sets the part size, by default it's 100K.
            downloadFileRequest.setPartSize(1024 * 1024 * 1);
            // Enable checkpoint. By default it's false.
            downloadFileRequest.setEnableCheckpoint(true);
            ossClient.downloadFile(downloadFileRequest);

        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteFile(String objectUrl) {
        String objectKeyFromUrl = getObjectKeyFromUrl(objectUrl);
        ossClient.deleteObject(BUCKET_NAME, objectKeyFromUrl);
    }

    @Override
    public String uploadFile(String dirName, String objectName, MultipartFile file) throws IOException {
        String fullObjectName = dirName + "/" + objectName;
        PutObjectResult result = ossClient.putObject(BUCKET_NAME, fullObjectName, file.getInputStream());
        return getAccessibleUrl(result.getETag(), fullObjectName);
    }

    private String getAccessibleUrl(String eTag, String objectName) {
        return "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + objectName;
    }

    // 从URL中提取OSS对象的Key
    private String getObjectKeyFromUrl(String url) {
        String[] parts = url.split("/", 4);
        return parts.length == 4 ? parts[3] : "";
    }
}
